package cn.lili.modules.system.serviceimpl;

import cn.hutool.core.text.CharSequenceUtil;
import cn.lili.cache.Cache;
import cn.lili.cache.CachePrefix;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.modules.system.entity.dos.SensitiveWords;
import cn.lili.modules.system.mapper.SensitiveWordsMapper;
import cn.lili.modules.system.service.SensitiveWordsService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 敏感词业务层实现
 *
 * @author Bulbasaur
 * @since 2020/11/17 8:02 下午
 */
@Service
@RequiredArgsConstructor
public class SensitiveWordsServiceImpl extends ServiceImpl<SensitiveWordsMapper, SensitiveWords> implements SensitiveWordsService {
    private final Cache<List<String>> cache;

    @Override
    public void resetCache() {
        List<SensitiveWords> sensitiveWordsList = this.list();

        if (sensitiveWordsList == null || sensitiveWordsList.isEmpty()) {
            return;
        }
        List<String> sensitiveWords = sensitiveWordsList.stream().map(SensitiveWords::getSensitiveWord).collect(Collectors.toList());
        cache.put(CachePrefix.SENSITIVE.getPrefix(), sensitiveWords);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveSensitiveWords(SensitiveWords sensitiveWords) {
        LambdaQueryWrapper<SensitiveWords> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SensitiveWords::getSensitiveWord, sensitiveWords.getSensitiveWord());
        queryWrapper.ne(CharSequenceUtil.isNotEmpty(sensitiveWords.getId()), SensitiveWords::getId, sensitiveWords.getId());
        if (this.getOne(queryWrapper) != null) {
            throw new ServiceException(ResultCode.SENSITIVE_WORDS_EXIST_ERROR);
        }
        return this.saveOrUpdate(sensitiveWords);
    }
}